local BasePlugin   = require "kong.plugins.base_plugin"
local CustomHandler    = BasePlugin:extend()
CustomHandler.VERSION  = "1.0.0"
CustomHandler.PRIORITY = 10
cjson = require "cjson"
function CustomHandler:new()
    CustomHandler.super.new(self, "gfb-admin-plugin")
end
function CustomHandler:init_worker()
    CustomHandler.super.init_worker(self)
end
function CustomHandler:preread(config)
    CustomHandler.super.preread(self)
end
function CustomHandler:certificate(config)
    CustomHandler.super.certificate(self)
end
function CustomHandler:rewrite(config)
    CustomHandler.super.rewrite(self)
end
function CustomHandler:access(config)
    CustomHandler.super.access(self)
    if kong.request.get_header("authorization") == nil then
        return kong.response.exit(401,'{"code":401,"msg":"请登录","data":[]}')
    end
    local method = kong.request.get_method()
    local host = kong.request.get_forwarded_host()
    local path = kong.request.get_path()
    local requestBody = "method="..method.."&host="..host.."&path="..path
    local appToken = kong.request.get_header("app-token")
    local authorization = kong.request.get_header("authorization")
    local restyHttp = require "resty.http"
    local httpc = restyHttp.new()
    local res = httpc:request_uri(config.url, {
        method = "POST",
        body = requestBody,
        headers = {
             ["authorization"] = authorization,
             ["app-token"] = appToken,
             ["Content-Type"] = "application/x-www-form-urlencoded"
        }
    })
    local data = cjson.decode(res.body)
    if data["code"] ~= 0 then
      return kong.response.exit(401,res.body, {
        ["Content-Type"] = "application/json",
      })
    end
end
return CustomHandler